package com.tim.app.ui.activity.setting;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.SmoothSwitchScreenUtil;
import com.application.library.util.StringUtil;
import com.application.library.util.TimeUtil;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.manager.WindowUtils;
import com.tim.app.server.api.API_App;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.LoginResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UploadResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.ui.widget.imagepick.bean.ImageItem;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 完善个人信息
 */
public class PerfectPersonInfomationActivity extends BaseActivity {

    private static final String TAG = "PerfectPersonInfomationActivity";

    private EditText et_input_nickname;
    private String nickName;
    private Button btConfrim;
    private RelativeLayout rlSelectAvatar;
    private RoundedImageView rivAvatar;
    private TextView tvSelectPic;
    private TextView tvDateYear;
    private TextView tvDateMonth;
    private TextView tvDateDay;

    private int type;
    private String userId;
    private User user;

    private RadioGroup rgSex;

    private Bitmap avatar;

    private String avatarPath;
    ImagePickerManager imagePicker;

    int currentYear;
    int currentMonth;
    int currentDay;

    DatePickerDialog datePickerDialog;
    DatePicker picker;


    private final int MAX_NAME = 8;
    private final int MAX_NAME_BYTE = 2 * MAX_NAME;

    private final int MIN_NAME = 2;
    private final int MIN_NAME_BYTE = 2 * MIN_NAME;

    private String currentName = "";
    private int indexName;

    /**
     *
     *
     * @param context
     * @param type
     */
    public static void start(Activity context, User user, int type, int requestCode) {
        Intent intent = new Intent(context, PerfectPersonInfomationActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("user", user);
        context.startActivityForResult(intent, requestCode);
    }


    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
        SmoothSwitchScreenUtil.smoothSwitchScreen(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_perfect_person_infomation;
    }

    @Override
    public void initView() {
        et_input_nickname = (EditText) findViewById(R.id.et_input_nickname);
        rlSelectAvatar = (RelativeLayout) findViewById(R.id.rlSelectAvatar);
        rivAvatar = (RoundedImageView) findViewById(R.id.rivAvatar);
        tvSelectPic = (TextView) findViewById(R.id.tvSelectPic);
        rlSelectAvatar.setOnClickListener(this);
        et_input_nickname.addTextChangedListener(new MyEditChangeListener());
        btConfrim = (Button) findViewById(R.id.btConfrim);
        findViewById(R.id.iv_back).setOnClickListener(this);
        btConfrim.setOnClickListener(this);
        rgSex = (RadioGroup) findViewById(R.id.rgSex);
        tvDateYear = (TextView) findViewById(R.id.tvDateYear);
        tvDateYear.setOnClickListener(this);
        tvDateMonth = (TextView) findViewById(R.id.tvDateMonth);
        tvDateMonth.setOnClickListener(this);
        tvDateDay = (TextView) findViewById(R.id.tvDateDay);
        tvDateDay.setOnClickListener(this);

        imagePicker = ImagePickerManager.ins();
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(false);
        if (android.os.Build.MODEL.contains("HM NOTE")) {
            imagePicker.setShowCamera(false);
        }
        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                ToastUtil.showToast("注册成功后，性别不可修改");
            }
        });

    }

    private class MyEditChangeListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (StringUtil.getTotalBytes(et_input_nickname.getText().toString().trim()) <= MAX_NAME_BYTE) {
                currentName = et_input_nickname.getText().toString().trim();
            }
            if (!StringUtil.checkEmojText(et_input_nickname.getText().toString().trim())) {
                indexName = et_input_nickname.getSelectionStart();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String nameChange = et_input_nickname.getText().toString().trim();
            if (nameChange.contains("...")) {
                return;
            }
            if (StringUtil.checkEmojText(nameChange)) {
                ToastUtil.showToast("昵称不能包含特殊字符，只支持中英文、数字及下划线");
                et_input_nickname.setText(StringUtil.replaceEmojText(nameChange));
                et_input_nickname.setSelection(indexName);
                return;
            }
            if (StringUtil.getTotalBytes(nameChange) > MAX_NAME_BYTE) {
                if (StringUtil.getTotalBytes(nameChange) > MAX_NAME_BYTE) {
                    et_input_nickname.setError(getString(R.string.txt_info_name));
                }
            } else {
                if (StringUtil.getTotalBytes(nameChange) > MAX_NAME_BYTE) {
                    et_input_nickname.setText(currentName);
                    et_input_nickname.setSelection(currentName.length());
                    ToastUtil.showToast(RT.getString(R.string.txt_info_name));
                }
            }
            updateBtn();
        }
    }

    private void updateBtn() {
        if (!TextUtils.isEmpty(et_input_nickname.getText().toString().trim())) {
            btConfrim.setEnabled(true);
        } else {
            btConfrim.setEnabled(false);
        }
    }

    @Override
    public void initData() {
        if (getIntent().hasExtra("type")) {
            type = getIntent().getIntExtra("type", AppKey.TYPE_MOBILE_REGIST);
        }
        if (getIntent().hasExtra("user")) {
            user = (User) getIntent().getSerializableExtra("user");
            userId = user.getId();
        }
        if (null != user) {
            if (!TextUtils.isEmpty(user.getName())) {
                et_input_nickname.setText(user.getName());
            }
            if (!TextUtils.isEmpty(user.getImage())) {
                BitmapLoader.ins().loadBitmap(user.getImage(), 0, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                        super.onLoadingStarted(imageUri, view);
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        super.onLoadingFailed(imageUri, view, failReason);
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        super.onLoadingComplete(imageUri, view, loadedImage);
                        avatar = loadedImage;
                        tvSelectPic.setVisibility(View.GONE);
                        rivAvatar.setVisibility(View.VISIBLE);
                        rivAvatar.setImageBitmap(loadedImage);
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {
                        super.onLoadingCancelled(imageUri, view);
                    }
                });
            }
        }
        Calendar calendar = Calendar.getInstance();
        currentYear = calendar.get(Calendar.YEAR) - 27;
        currentMonth = calendar.get(Calendar.MONTH);
        currentDay = calendar.get(Calendar.DAY_OF_MONTH);
        tvDateYear.setText(String.valueOf(currentYear));
        tvDateMonth.setText(String.valueOf(currentMonth + 1));
        tvDateDay.setText(String.valueOf(currentDay));

        try {
            SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
            Date beginDate = new Date();
            Calendar date = Calendar.getInstance();
            date.setTime(beginDate);
            date.set(Calendar.YEAR, date.get(Calendar.YEAR) - 12);
            Date endDate = dft.parse(dft.format(date.getTime()));

            date.set(Calendar.YEAR, date.get(Calendar.YEAR) - 80);
            Date startDate = dft.parse(dft.format(date.getTime()));

            datePickerDialog = new DatePickerDialog(PerfectPersonInfomationActivity.this, AlertDialog.THEME_HOLO_LIGHT, Datelistener, currentYear, currentMonth, currentDay);
            picker = datePickerDialog.getDatePicker();
            picker.setMaxDate(endDate.getTime());
            picker.setMinDate(startDate.getTime());
            datePickerDialog.updateDate(currentYear, currentMonth, currentDay);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btConfrim) {
            nickName = et_input_nickname.getText().toString();
            if (!StringUtil.checkUserName(nickName)) {
                ToastUtil.showToast("昵称不能包含特殊字符，只支持中英文、数字及下划线");
                return;
            }
            uploadAvatar();
        } else if (v.getId() == R.id.iv_back) {
            finish();
        } else if (v.getId() == R.id.rlSelectAvatar) {
            SoftKeyboardUtil.hideSoftKeyboard(et_input_nickname);
            imagePicker.gallerySelectedPic(this);
        } else if (v.getId() == R.id.tvDateYear || v.getId() == R.id.tvDateMonth || v.getId() == R.id.tvDateDay) {
            datePickerDialog.show();//显示DatePickerDialog组件
        }
    }

    private void uploadAvatar() {
        String name = et_input_nickname.getText().toString();
        if (StringUtil.getTotalBytes(name) < MIN_NAME_BYTE) {
            ToastUtil.showToast(RT.getString(R.string.txt_info_name));
            return;
        }
        if (StringUtil.getTotalBytes(name) > MAX_NAME_BYTE) {
            ToastUtil.showToast(RT.getString(R.string.txt_info_name));
            return;
        }
        btConfrim.setEnabled(false);
        showLoadingDialog();
        if (null != avatar) {
            API_App.ins().uploadData(TAG, avatar, detailCallBack);
        } else if (!TextUtils.isEmpty(avatarPath)) {
            API_App.ins().uploadAvatarData(TAG, avatarPath, detailCallBack);
        } else {

            int sex = getSex();
            int age = getAge();
            String birthday = currentYear + "-" + currentMonth + "-" + currentDay;
            String constellation = TimeUtil.getConstellation(this, birthday, "yyyy-MM-dd");
            String imageUrl = "";
            if (sex == AppKey.SEX_MAN) {
                imageUrl = "http://moli2017.oss-cn-zhangjiakou.aliyuncs.com/user/userboy.png";
            } else if (sex == AppKey.SEX_WOMAN) {
                imageUrl = "http://moli2017.oss-cn-zhangjiakou.aliyuncs.com/user/usergirl.png";
            }
            regist(name, imageUrl, sex, age, birthday, constellation);
        }
    }

    private int getAge() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR) - currentYear;
    }

    /**
     * 性别
     *
     * @return
     */
    private int getSex() {
        if (rgSex.getCheckedRadioButtonId() == R.id.rbMan) {
            return 1;
        } else {
            return 2;
        }
    }

    StringResponseCallback detailCallBack = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK) {
                UploadResult result = new Gson().fromJson(resultValue, UploadResult.class);
                if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                    String url = result.getRes().getHashmap().getImgurl();
                    String name = et_input_nickname.getText().toString();
                    int sex = getSex();
                    int age = getAge();
                    String birthday = currentYear + "-" + currentMonth + "-" + currentDay;
                    String constellation = TimeUtil.getConstellation(PerfectPersonInfomationActivity.this, birthday, "yyyy-MM-dd");
                    regist(name, url, sex, age, birthday, constellation);
                }
            } else {
                btConfrim.setEnabled(true);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };


    String pwd = "";

    /**
     * 注册
     */
    private void regist(String name, String image, int sex, int age, String birthday, String constellation) {
        pwd = "";
        API_User.ins().perfectUserInfoSelective(TAG,this, userId,  name, image, sex, age, constellation, "",
                "", "", birthday, new StringResponseCallback() {
                    @Override
                    public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                        btConfrim.setEnabled(true);
                        hideLoadingDialog();
                        String vlaue = "";
                        if (type == AppKey.LOGIN_TYPE_SINA) {
                            vlaue = "wb";
                        } else if (type == AppKey.LOGIN_TYPE_QQ) {
                            vlaue = "qq";
                        } else if (type == AppKey.LOGIN_TYPE_WX) {
                            vlaue = "wx";
                        } else if (type == AppKey.LOGIN_TYPE_MOBILE) {
                            vlaue = "phone";
                        }
                        if (errCode == ResponseResult.ResultStatus.OK) {
                            if (!TextUtils.isEmpty(resultValue)) {
                                LoginResult result = new Gson().fromJson(resultValue, LoginResult.class);
                                if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                                    if (null != result.getRes().getHashmap().getUser()) {
                                        UserManager.ins().saveUserInfo(result.getRes().getHashmap().getUser());
                                    }
                                    if (!TextUtils.isEmpty(result.getRes().getHashmap().getAccessToken())) {
                                        UserManager.ins().saveToken(result.getRes().getHashmap().getAccessToken());
                                    }
                                    UserManager.ins().saveLoginType(vlaue);
                                    API_Statistics.ins().addRegistData(TAG, PerfectPersonInfomationActivity.this, vlaue);
                                    UserManager.ins().loginChat(result.getRes().getHashmap().getUser().getId());
                                    EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGIN, 0, 0, null);
                                    JPushInterface.setAlias(PerfectPersonInfomationActivity.this, UserManager.ins().getChatId(UserManager.ins().getUserId()), new TagAliasCallback() {
                                        @Override
                                        public void gotResult(int i, String s, Set<String> set) {

                                        }
                                    });
                                    Intent intent = new Intent(PerfectPersonInfomationActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    setResult(RESULT_OK);
                                    finish();
                                    WindowUtils.getInStance().clearList();
                                }
                            }
                        } else {
                            ToastUtil.showToast(errMsg);
                        }
                        return false;
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePickerManager.RESULT_CODE_ITEMS) {
            if (data == null) {
                return;
            }
            if (requestCode == ImagePickerManager.RESULT_CODE_GALLERY) {//从图库返回
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePickerManager.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < images.size(); i++) {
                    ImageItem item = images.get(i);
                    avatarPath = item.path;
                    tvSelectPic.setVisibility(View.GONE);
                    rivAvatar.setVisibility(View.VISIBLE);
                    avatar = null;
                    BitmapLoader.ins().loadLocalImage(avatarPath, rivAvatar);
                }
            }
        } else if (requestCode == ImagePickerManager.REQUEST_CODE_TAKE) {
            //发送广播通知图片增加了
            ImagePickerManager.galleryAddPic(this, imagePicker.getTakeImageFile());
            avatarPath = imagePicker.getTakeImageFile().getAbsolutePath();
            tvSelectPic.setVisibility(View.GONE);
            rivAvatar.setVisibility(View.VISIBLE);
            avatar = null;
            BitmapLoader.ins().loadLocalImage(avatarPath, rivAvatar);
        }
    }

    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
        /**params：view：该事件关联的组件
         * params：myyear：当前选择的年
         * params：monthOfYear：当前选择的月
         * params：dayOfMonth：当前选择的日
         */
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {


            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            //更新日期
            updateDate(year, monthOfYear, dayOfMonth);

        }

        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate(int year, int monthOfYear, int dayOfMonth) {
            //在TextView上显示日期
            currentYear = year;
            currentMonth = monthOfYear + 1;
            currentDay = dayOfMonth;
            tvDateYear.setText(String.valueOf(currentYear));
            tvDateMonth.setText(String.valueOf(currentMonth));
            tvDateDay.setText(String.valueOf(currentDay));
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        if (et_input_nickname != null) {
            SoftKeyboardUtil.hideSoftKeyboard(et_input_nickname);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

}
